package com.ehome.poct.core.api.dto.order;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.ehome.exception.BizException;
import com.ehome.poct.core.api.dto.common.DomainBizCodeEnum;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 订单号
 * @author gyl
 * @since 2022/3/5 14:15
 **/
@Data
public class OrderNo {
    private final String value;
    private static final String DATE_FORMAT = "yyMMddHHmmss";

    public OrderNo(String deviceSno) {
        // 验证
        if (null == deviceSno) { throw new BizException(DomainBizCodeEnum.NO_DEVICE); }
        this.value = generateOrderNo(deviceSno);
    }

    /**
     * 根据设备编号生成订单号
     * 规则：设备编号 + 当前时间（年份取后两位）+ 随机4位数字
     *
     * @param deviceSno     设备编号
     * @return 返回32位订单编号
     */
    private String generateOrderNo(String deviceSno) {
        StringBuffer orderNo = new StringBuffer(deviceSno);
        orderNo.append(DateUtil.format(LocalDateTime.now(), DATE_FORMAT));
        orderNo.append(RandomUtil.randomNumbers(4));
        return orderNo.toString();
    }
}
